//
//  SearchViewController.m
//  BeanTrip
//
//  Created by dlios on 15-7-13.
//  Copyright (c) 2015年 PandaGroup. All rights reserved.
//

#import "SearchViewController.h"
#define WIDTH ([UIScreen mainScreen].bounds.size.width/375)
#define HEIGH ([UIScreen mainScreen].bounds.size.height/667)
#import "FirstModel.h"
#import "HTTPTool.h"
#import "SearchCell.h"
#import "UIImageView+WebCache.h"
#import "TravelNotesViewController.h"
#import "MBProgressHUD.h"


@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UITextFieldDelegate>
@property (nonatomic, strong)UISearchBar *myBar;
@property (nonatomic, strong)UITableView *table;
@property (nonatomic, strong)NSMutableArray *allarray;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, retain)UIAlertView *alert;

@end

@implementation SearchViewController

- (void)dealloc
{
    [_myBar release];
    [_table release];
    [_allarray release];
    [_HUD release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title =@"搜索";
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    self.view.backgroundColor=[UIColor whiteColor];
    //更改导航栏的默认返回bar,保留箭头,并将颜色改为白色
    UIBarButtonItem *bar=[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem=bar;
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    //将导航栏的标题更改大小和颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
    
    
    
    
    
    

    
    self.myBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10*WIDTH, 35*HEIGH, 375*WIDTH - 80*WIDTH, 25*HEIGH)];
    self.myBar.delegate = self;
    [self.view addSubview:self.myBar];
    self.myBar.barTintColor = [UIColor whiteColor];
    self.myBar.layer.borderWidth = 2;
    self.myBar.backgroundColor = [UIColor whiteColor];
    self.myBar.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.myBar.layer.cornerRadius = 8;
    self.myBar.layer.masksToBounds= YES;
    self.myBar.delegate = self;
    
    //    self.myBar.barStyle =  UIBarStyleDefault;
    self.myBar.placeholder = @"请输入要搜索的游记";

    
    self.myBar.keyboardType = UIKeyboardTypeDefault;
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 65*HEIGH, 375*WIDTH, 667*HEIGH)];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.view addSubview:button];
    button.frame = CGRectMake(320*WIDTH, 33*HEIGH, 40*WIDTH, 30*HEIGH);
    [button setTitleColor:[UIColor
                           orangeColor] forState:(UIControlStateNormal)];
    button.layer.cornerRadius = 8;
    //[button setTitle:@"取消" forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(popAction) forControlEvents:(UIControlEventTouchUpInside)];
    UILabel *ButtonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40*WIDTH, 30*HEIGH)];
    ButtonLabel.text = @"取消";
    ButtonLabel.font = [UIFont systemFontOfSize:17*HEIGH];
    ButtonLabel.textColor = [UIColor orangeColor];
    [button addSubview:ButtonLabel];
    
//    [self createData];
   
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    /**
     小菊花
     
     :returns: 是
     */
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"加载中";
    [self.HUD show:YES];

    


    
    
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/search/?key=%@&start=0&count=100", self.myBar.text];
    NSString *strUtf = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url_string = strUtf;

    
    self.allarray = [NSMutableArray array];
[HTTPTool get:url_string body:nil httpResult:JSON success:^(id result) {
    NSDictionary *dic = result;
    NSMutableArray *Array = [dic objectForKey:@"trips"];
    for (NSDictionary *allDic in Array) {
        FirstModel *first = [[FirstModel alloc] initWithDic:allDic];
        [self.allarray addObject:first];
        [first release];
        
    }
    if (self.allarray.count == 0) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有搜索结果" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    [self.table reloadData];
    //移除菊花
    [self.HUD removeFromSuperview];
    
} failure:^(NSError *error) {
   [self.HUD removeFromSuperview];
    self.alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [self.alert show];
    [self.alert release];
    NSLog(@"%@",error);

    
}];
[self.myBar resignFirstResponder];

}





- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allarray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuse = @"reuse";
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[SearchCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    FirstModel *first = self.allarray[indexPath.row];

    [cell.myImageV sd_setImageWithURL:[NSURL URLWithString:first.cover_image_default]];
    cell.label1.text = first.name;
    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90 * HEIGH;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelNotesViewController *travel = [[TravelNotesViewController alloc] init];
    FirstModel *first = self.allarray[indexPath.row];
    //id传过去
    travel.detailId = first.turnNextId;
    //标题传过去
    travel.titleName = first.name;
    [self.navigationController pushViewController:travel animated:YES];

}


- (void)popAction
{
    [self.navigationController popViewControllerAnimated:NO];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
